import { useState, useEffect } from "react";
import { Form, Radio, Input, Button, DatePicker, Modal, Select } from "antd";

import dayjs from "dayjs";

import locale from "antd/es/date-picker/locale/zh_CN";

import "dayjs/locale/zh-cn";
import { req, formaData } from "@/common/methods";

import Loading from "../Loading";

interface Record {
  id: number;
  doc_id: string;
  time: string;
  method: number;
  user_id: number;
  goods_id: number;
  before_count: number;
  change_count: number;
  after_count: number;
  depart: number;
  requ: string;
  empl: string;
}

const EditComponent = (props: { record: Record; doClose: () => void }) => {
  const [loading, setLoading] = useState(true);
  const [departData, setDepartData] = useState([]);
  const [supplierData, setSupplierData] = useState([]);
  const fetchBaseData = () => {
    req("/api/depart/get")
      .then((data: any) => {
        setDepartData(data);
        return req("/api/suppliers/get");
      })
      .then((data: any) => {
        setSupplierData(data);
        setLoading(false);
      })
      .catch((error) => {
        Modal.error({
          title: "页面初始化错误",
          content: <>无法获取基础数据{}</>,
        });
      });
  };
  useEffect(() => {
    fetchBaseData();
  }, []);
  const { record, doClose } = props;
  const initRecord = { ...record, time: dayjs(record.time) };
  console.log(record);
  const [form] = Form.useForm();
  const onFinish = (values: any) => {
    console.log("提交", formaData(values.time.$d));
    values = {
      ...values,
      time: (() => {
        return formaData(values.time.$d);
      })(),
    };
    req("/api/storage_edit", { ...values }, "post")
      .then(() => {
        //console.log("成功");
        Modal.success({
          title: "修改成功",
          content: (
            <>
              <div>
                您已将
                {editBasis === 1
                  ? `惟一标识符为${values.id}`
                  : `单据为${values.doc_id}`}
                的数据修改：
              </div>
              <div>
                <ul>
                  {(editBasis === 1
                    ? ["requ", "empl", "reason", "remark"]
                    : ["method", "time", "depart", "requ", "empl"]
                  ).map((item) => (
                    <li
                      key={item}
                      style={{ display: "flex", justifyContent: "flex-start" }}
                    >
                      <span
                        style={{
                          width: "80px",
                          textAlign: "right",
                          fontWeight: "bold",
                        }}
                      >
                        {item}:
                      </span>
                      <span style={{ flex: 1, padding: "0 15px" }}>
                        <span style={{ color: "lightgray" }}>
                          `{"" + (record as any)[item]} `
                        </span>
                        <span style={{ color: "pink" }}> -&gt; </span>`
                        {(values as any)[item]}`
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            </>
          ),
          width: 500,
          onOk() {
            Modal.destroyAll();
            doClose();
          },
        });
      })
      .catch((error) => {
        Modal.error({ title: "提交失败", content: <>{"" + error}</> });
      });
  };
  const [editBasis, setEditBasis] = useState(0);
  const [isIn] = useState<boolean>(record.change_count > 0);
  const [method, setMethod] = useState<number>(record.method);
  const toOptions = (arr: any) => {
    if (!Array.isArray(arr)) {
      return [];
    }
    const res = arr.map((item: any) => {
      return {
        value: item?.id,
        label: item?.name,
      };
    });
    // res.push({
    //   value: 0,
    //   label: "（未知）",
    // });
    return res;
  };
  return (
    <>
      {loading ? (
        <Loading />
      ) : (
        <>
          <Form
            form={form}
            onFinish={onFinish}
            onFinishFailed={() => {
              Modal.error({
                title: "无法提交",
                content: <>请检查是否规范填写</>,
              });
            }}
            initialValues={initRecord}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              name="edit_basis"
              label="修改依据"
              rules={[{ required: true, message: "修改依据不能为空" }]}
            >
              <Radio.Group
                onChange={(e) => {
                  setEditBasis(e.target.value);
                  form.setFieldsValue(initRecord);
                  setMethod(initRecord.method);
                }}
              >
                <Radio value={1}>本条数据:[{record.id}]</Radio>
                <Radio value={2}>单号:{record.doc_id}</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="id"
              label="惟一识别码"
              rules={[{ required: true, message: "惟一标识符不能为空" }]}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item
              name="doc_id"
              label="单号"
              rules={[{ required: true, message: "单号不能为空" }]}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item
              name="method"
              label="方式"
              rules={[{ required: true, message: "方式不能为空" }]}
            >
              <Radio.Group
                disabled={editBasis !== 2}
                onChange={(e) => setMethod(e.target.value)}
              >
                <Radio value={10}>{isIn ? "进货" : "退货"}</Radio>
                <Radio value={20}>{isIn ? "退库" : "领用"}</Radio>
                <Radio value={30}>{isIn ? "盘盈" : "盘亏"}</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="time"
              label="时间"
              rules={[{ required: true, message: "时间不能留空" }]}
            >
              {/* <DatePicker /> */}
              {/* <Input disabled={editBasis !== 2} /> */}
              <DatePicker
                locale={locale}
                showTime={{ format: "YYYY-MM-DD HH:mm:ss" }}
                disabled={editBasis !== 2}
              />
            </Form.Item>
            {method !== 30 && (
              <>
                <Form.Item
                  name="depart"
                  label={method === 10 ? "供货商" : "部门"}
                  rules={[{ required: true, message: "当前字段不能留空" }]}
                >
                  {/* <Input disabled={editBasis !== 2} /> */}
                  <Select
                    options={[
                      ...toOptions(method === 10 ? supplierData : departData),
                    ]}
                    disabled={editBasis !== 2}
                  />
                </Form.Item>
                <Form.Item
                  name="requ"
                  label={{ 10: "经手人", 20: "申请人" }[method] || method}
                  rules={
                    method === 20
                      ? [{ required: true, message: "当前字段不能留空" }]
                      : []
                  }
                >
                  <Input disabled={![1, 2].includes(editBasis)} />
                </Form.Item>
                <Form.Item
                  name="empl"
                  label={
                    isIn
                      ? { 10: "进货人", 20: "交回人" }[method] || method
                      : { 10: "退货人", 20: "领用人" }[method] || method
                  }
                  rules={
                    method === 20
                      ? [{ required: true, message: "当前字段不能留空" }]
                      : []
                  }
                >
                  <Input disabled={![1, 2].includes(editBasis)} />
                </Form.Item>{" "}
              </>
            )}
            {method === 30 && (
              <Form.Item
                name="reason"
                label="事由"
                hidden={editBasis !== 1}
                rules={
                  method === 30
                    ? [{ required: true, message: "当前字段不能留空" }]
                    : []
                }
              >
                <Input />
              </Form.Item>
            )}
            <Form.Item name="remark" label="备注" hidden={editBasis !== 1}>
              <Input />
            </Form.Item>
            <Form.Item style={{ display: "flex", justifyContent: "center" }}>
              <Button type="primary" htmlType="submit">
                提交修改
              </Button>
            </Form.Item>
          </Form>
        </>
      )}
    </>
  );
};
export default EditComponent;
